<template>
    <div>
        <nav-bar>
            <template v-slot:default>
                商品分类
            </template>
        </nav-bar>

        <div id="mainbox">
            <div class="ordertab"> 
                <van-tabs v-model="active" @click="tabClick">
                    <van-tab title="销量排序"></van-tab>
                    <van-tab title="价格排序"></van-tab>
                    <van-tab title="评论排序"></van-tab>
                </van-tabs>
            </div>

            <van-sidebar class="leftmenu" v-model="activeKey">
                <van-collapse v-model="activeName" accordion="">
                    <van-collapse-item v-for="(item, index) in categories.slice(0,5)" 
                        :key="(index,item.id)" 
                        :title="item.name" 
                            :name="item.name">
                    
                        <van-sidebar-item v-for="sub in item.children" :title="sub.name" :key="sub.id" @click="getGoods(sub.id)"></van-sidebar-item>
                
                        </van-collapse-item>
                </van-collapse>   
            </van-sidebar>

            <div class="goodslist">
                <div class="content">
                    <van-card 
                        v-for="item in showGoods" :key="item.id"
                        @click="itemClick(item.id)"
                        :num="item.comments_count" 
                        :tag="item.comments_count >= 0? '流行' : '标签'" 
                        :price="item.price" 
                        :desc="item.updated_at" 
                        :title="item.title" 
                        :thumb="item.cover_url"
                        :lazy-load="true">
                    </van-card>
                </div>
            </div>
        </div>

        <back-top @bTop="bTop" v-show="isShowBackTop"></back-top>
    </div>
</template>

<script>
    import NavBar from '@/components/common/navbar/NavBar.vue';
    import BackTop from 'components/common/backtop/BackTop.vue';
    import {ref, reactive, onMounted, computed, watchEffect, nextTick} from 'vue';
    import { useRouter } from 'vue-router';
    import {getCategory, getCategoryGoods} from "network/category";
    import BScroll from 'better-scroll';

    export default {
        name: "Categroy",
        setup() {
            // 获取路由器
            const router = useRouter();

            let activeKey = ref(0);
            let activeName = ref(1);
            let active = ref(1);
            let categories = ref([]);
            let isShowBackTop = ref(false);

            //当前的排序条件
            let currentOrder = ref('sales');
            //当前的分类ID
            let currentCid = ref(0);

            //数据模型
            const goods = reactive({
                sales:{page:1, list:[]},
                price:{page:1, list:[]},
                comments_count:{page:1, list:[]},
            })

            //定义一个显示商品数据通过计算属性
            const showGoods = computed(()=>{
                return goods[currentOrder.value].list;
            })

            //获取到分类页面的详细数据
            const init = () =>{
                //获取到通过销量排序的数据
                getCategoryGoods('sales', currentCid.value).then(res=>{
                    goods.sales.list = res.goods.data;
                })

                //获取到通过价格排序的数据
                getCategoryGoods('price', currentCid.value).then(res=>{
                    goods.sales.list = res.goods.data;
                })

                //获取到通过评论数量排序的所有数据
                getCategoryGoods('comments_count', currentCid.value).then(res=>{
                    goods.sales.list = res.goods.data;
                })
            }

            let bscroll = reactive({});

            onMounted(()=>{
                getCategory().then(res=>{
                    categories.value = res.categories;
                })

                //页面加载完所有数据时调用该方法
                init();

                //创建BetterScroll对象
                bscroll = new BScroll(document.querySelector('.goodslist'),{
                    probeType: 3,  //0，1，2，3  3是代表了只要在运行时就触发scroll事件
                    click: true,   //是否允许点击事件触发
                    pullUpLoad: true //上拉加载更多，默认是假
                });

                //使用触发滚动事件
                bscroll.on('scroll',(position)=>{
                    // console.log(banref.value.offsetHeight);
                    // console.log(position.y);

                    isShowBackTop.value  = (-position.y) > 300;
                })

                //上拉加载数据,触发pullingup
                bscroll.on("pullingUp",()=>{
                    console.log('上拉加载更多.....');
                    // const page = goods[currentType.value].page + 1;  
                    // getHomeGoods(currentType.value, page).then(res=>{
                    //     goods[currentType.value].list.push(...res.goods.data);
                    //     goods[currentType.value].page += 1;
                    // })

                    const page = goods[currentOrder.value].page + 1;

                    //更新数据
                    getCategoryGoods(currentOrder.value, currentCid.value).then(res=>{
                        goods[currentOrder.value].list.push(...res.goods.data);
                        goods[currentOrder.value].page += 1;
                    })


                    //完成上拉加载，等数据请求加载完成之后，要将新加载出来的数据重新展示在页面上
                    bscroll.finishPullUp();

                    //加载完成之后重新 计算高度
                    nextTick(()=>{
                        //重新计算高度
                        bscroll && bscroll.refresh();
                    })

                    console.log("conten:"+document.querySelector('.content').clientHeight);
                    console.log("当前类型:"+currentOrder.value+",当前页:"+page);
                })


            })

            //排序选项卡
            const tabClick = (index)=>{
                let orders = ['sales','price','comments_count'];

                currentOrder.value = orders[index];

                //更新数据
                getCategoryGoods(currentOrder.value, currentCid.value).then(res=>{
                    goods[currentOrder.value].list = res.goods.data;
                    nextTick(()=>{
                    //重新计算高度
                     bscroll && bscroll.refresh();
                    })
                })

                console.log("当前的分类ID:" + currentCid.value);
                console.log("排序的序号：" + currentOrder.value);
            }

            //通过分类得到get商品
            const getGoods = (cid) =>{
                currentCid.value = cid;

                init();
                console.log("当前的分类ID:" + currentCid.value);
                console.log("排序的序号：" + currentOrder.value);
            }

             //监听任何一个数据的变化
             watchEffect(()=>{
                nextTick(()=>{
                    //重新计算高度
                   bscroll && bscroll.refresh();
                })
            })

            //返回顶部方法
            const bTop = ()=>{
                bscroll.scrollTo(0, 0, 500);
            }

            return {
                activeKey,
                categories,
                activeName,
                active,
                tabClick,
                currentOrder,
                currentCid,
                getGoods,
                goods,
                showGoods,
                bscroll,
                isShowBackTop,
                bTop,
                itemClick:(id)=>{
                    router.push({path:'/detail',query:{id}});
                }
            }
        },
        components: {
            NavBar,
            BackTop
        }
    }
</script>

<style scoped lang="scss">
#mainbox {
    margin-top: 45px;
    display: flex;
    .ordertab {
        flex: 1;
        float: right;
        height: 50px;
        z-index: 9;
        position: fixed;
        top: 45px;
        right: 0;
        left: 130px;
    }
    .leftmenu {
        position: fixed;
        top: 95px;
        left: 0;
        width: 130px;
    }
    .goodslist {
        flex: 1;
        position: absolute;
        top: 100px;
        left: 130px;
        right: 0;
        height: 100vh;
        padding: 10px;
        text-align: left !important;
        .content {
            padding-top: 10px;
        }

        // .van-card_content {
        //     text-align: left !important;
        //     float: left;
        // }
    }
}

.van-card_thumb {
    width: 68px !important;
}
</style>